<template>
<div class="event-header">
  <div class="left">
    <div :class="['change-alarm',{'diabled':prevDisabled}]" @click="prevAlarm">
      <span style="margin-right: 6px;font-size: 12px" class="iconfont icon-PC_icon_shangyishijian"></span>
      <span>上一事件</span>
    </div>
  </div>
  <div class="right">
    <el-button v-if="pageType === 'recycleBin' || pageType === 'eventQuery'" class="fs-14 mr-10 down-file" type="text" @click.stop="downAlarmFile"
               v-hasPermi="['export:alarm:file']"
               :disabled="fileLoading">
      <i class="fs-14 pt-2 iconfont icon-daochu"></i>
      <i class="ml-6">导出告警文件</i>
      <i v-show="fileLoading" class="ml-6 el-icon-loading"></i>
    </el-button>
    <el-button
      class="down-img"
      type="text"
      v-if="showDownVideo"
      v-hasPermi="['localEvent:detail:downVideo']"
      @click.stop="downAlarmVideo"
      style="height: 100%"
    >
      <span style="margin-right: 4px;font-size: 12px;margin-top: 1px" class="icon-pc_icon_xiazaigaojingshipin iconfont"></span>
      <span>下载告警视频</span>
      <i v-show="videoLoading" class="ml-5 el-icon-loading"></i>
    </el-button>
    <el-button
      style="height: 100%;margin-right: 4px;"
      class="down-img"
      title="下载告警图片"
      type="text"
      v-hasPermi="['wxDetail:alarm:downImg','localEvent:detail:downImg']"
      @click="downAlarmImg">
      <span style="margin-right: 4px;font-size: 12px;margin-top: 1px" class="icon-pc_icon_xiazaigaojingtupian iconfont"></span>
      下载告警图片
      <i v-show="imgLoading" class="el-icon-loading"></i>
    </el-button>
    <el-divider direction="vertical" style="padding:0px 12px"></el-divider>
    <div :class="['change-alarm',{'diabled':nextDisabled}]" @click="nextAlarm">
      <span style="margin-left: 4px">下一事件</span>
      <span style="margin-left: 6px;font-size: 12px" class="iconfont icon-PC_icon_xiayishijian"></span>
    </div>
  </div>
</div>
</template>

<script>
import {getQueryString} from "@/utils/common";
import { getOrderList } from "@/api/modules/eventManagement/satelliteAlarm.js";
import {downLoadZipPost} from "@/api/modules/eventManagement/eventManagement";
import html2canvas from "html2canvas";
import eventBus from "@/utils/event-bus";
export default {
  name: "eventHeader",
  data(){
    return {
      alarmList:[],
      alarmIndex:null, // 事件索引
      pageData:null, // 分页信息
      orderList:null, // 数据信息
      searchParams:null, // 查询条件
      prevDisabled:false, // 是否禁用上一事件
      nextDisabled:false, // 是否禁用下一事件
      imgLoading:false,
      videoLoading:false,
      page:null,
      fileLoading: false,
      pageType: '',
      mapDom: null
    }
  },
  props:{
    orderData:{
      type:Object,
      default:() => ({})
    },
    getOrderList:{
      type:Function,
      default:() => ({})
    }
  },
  created() {
    this.initData();
  },
  mounted() {
    this.pageType = this.$route.query.pageType
    eventBus.$on('click-footer-map',this.moveMapDom)
    eventBus.$on('move-map-to-other-view',this.setMapElement)
  },
  computed:{
    showDownVideo(){
      return !location.href.includes("/satelliteAlarmDetail") && ['1','3','4','8','9','10'].includes(this.orderData.warningSource)
    },
    exportSource() {
      if(this.pageType === 'eventQuery' || getQueryString('page') === '12' || getQueryString('page') === '13') {
        return '4'
      }
      if(this.pageType === 'recycleBin' && getQueryString('page') === '11') {
        return '5'
      }
      if(this.pageType === 'custOperate') {
        return '6'
      }
    }
  },
  watch:{
    alarmIndex(){ // 监听事件索引，查询当前事件是否存在上一事件下一事件
      this.page = this.$route.query.page;
      let currentAlarmIndex = (this.pageData.currentPage - 1) * this.pageData.page_size + this.alarmIndex + 1; // 当前告警事件在所有事件中的序号
      this.nextDisabled = currentAlarmIndex === this.pageData.total;
      this.prevDisabled = this.alarmIndex === 0 && this.pageData.currentPage === 1;
      if(location.href.includes('eventQueryDetail')) {
        setTimeout(()=>{
          const dom = document.querySelector('.medias-map-component .event_map_big')
          this.mapDom = dom;
          this.moveMapDom()
        },500)
      }
    }
  },
  methods:{
    /**
     * 上一事件
     */
    async prevAlarm(){
      if(this.prevDisabled) { return }; // 设置边界
      this.alarmIndex = this.alarmIndex - 1;
      if(!this.orderList[this.alarmIndex]) {
        await this.getViewDataSource(true);
        this.alarmIndex = this.pageData.page_size - 1; // 索引重置最大值
      }
      this.orderList[this.alarmIndex].polygonOperate = this.orderList[this.alarmIndex].polygonOperateList;
      this.$emit('update:orderData', this.orderList[this.alarmIndex])
      let orderData = this.orderList[this.alarmIndex]
      let pointData = {
        position:[Number(orderData.longitude),Number(orderData.latitude)],
        positionMonitor:[Number(orderData.videoLongitude),Number(orderData.videoLatitude)].filter(item=>item)

      }
      this.$emit('getMapPoint',pointData)
    },
    /**
     * 下一事件
     */
    async nextAlarm(){
      if(this.nextDisabled) { return }; // 设置边界
      this.alarmIndex = this.alarmIndex + 1;
      if(!this.orderList[this.alarmIndex]) {
        await this.getViewDataSource(false);
        this.alarmIndex = 0; // 索引归0
      }
      this.orderList[this.alarmIndex].polygonOperate = this.orderList[this.alarmIndex].polygonOperateList;
      this.$emit('update:orderData', this.orderList[this.alarmIndex])
      let orderData = this.orderList[this.alarmIndex]
      let pointData = {
        position:[Number(orderData.longitude),Number(orderData.latitude)],
        positionMonitor:[Number(orderData.videoLongitude),Number(orderData.videoLatitude)].filter(item=>item)

      }
      this.$emit('getMapPoint',pointData)
    },
    /**
     * 接收列表过来的信息
     */
    initData(){
      if(this.$route.query.pageType === 'WxDetail') {
        let alarmCode = sessionStorage.getItem("WXalarmCode");
        this.searchParams = JSON.parse(sessionStorage.getItem("WXsearchParams"));
        this.orderList =  JSON.parse(sessionStorage.getItem('WXorderList'));
        this.pageData = JSON.parse(sessionStorage.getItem('WXpageData'));
        let orderData = this.orderList.filter((item,index)=>{
          if(item.alarmCode === alarmCode) {
            this.alarmIndex = index;
            return item;
          }
        })[0];
        this.$emit('update:orderData',orderData);
      }else {
        if(this.$route.query.pageType === 'eventQuery') {
          this.orderList =  JSON.parse(sessionStorage.getItem('eventLocalOrderList'));
          this.pageData = JSON.parse(sessionStorage.getItem('eventLocalPageData'));
          this.searchParams = JSON.parse(sessionStorage.getItem("eventLocalSearchParams"));
        }
        if(this.$route.query.pageType === 'recycleBin') {
          this.orderList =  JSON.parse(sessionStorage.getItem('recyLocalOrderList'));
          this.pageData = JSON.parse(sessionStorage.getItem('recyLocalPageData'));
          this.searchParams = JSON.parse(sessionStorage.getItem("recyLocalSearchParams"));
        }
        if(this.$route.query.pageType === 'custOperate') {
          this.orderList =  JSON.parse(sessionStorage.getItem('custLocalOrderList'));
          this.pageData = JSON.parse(sessionStorage.getItem('custLocalPageData'));
          this.searchParams = JSON.parse(sessionStorage.getItem("custLocalSearchParams"));
        }
        this.orderList.filter((item,index)=>{
          if(this.$route.query.orderId === item.warningOrderId) {
            this.alarmIndex = index;
          }
        })
        let orderData = JSON.parse(sessionStorage.getItem(this.$route.query.orderId));
        orderData.polygonOperate = orderData.polygonOperateList;
        console.log(orderData,"orderData")
        this.$emit('update:orderData',orderData);
        let pointData = {
          position:[Number(orderData.longitude),Number(orderData.latitude)],
          positionMonitor:[Number(orderData.videoLongitude),Number(orderData.videoLatitude)].filter(item=>item)
        }
        this.$emit('getMapPoint',pointData)
      }

    },
    /**
     * 查询列表
     * @param flag true 上一事件  false 下一事件
     */
    async getViewDataSource(flag){
      if(flag) {
        this.searchParams.pageNum = this.searchParams.pageNum - 1;
      }else {
        this.searchParams.pageNum = this.searchParams.pageNum + 1;
      }
      this.$emit('update:loading',true);
      const result = await this.getOrderList(this.searchParams);
      this.$emit('update:loading',false);
      if(result.code === 200) {
        this.pageData.currentPage = this.searchParams.pageNum;
        this.orderList = result.data.list;
        this.pageData.total = result.data.total;
      }
    },
    downAlarmImg(){
      if(this.$route.query.pageType === 'WxDetail') {
        this.imgLoading = true;
        this.$emit('downAlarmImg',this.dowImgsCallback);
      }else {
        let params = {};
        params.downLoadType = '0';
        params.imgReq = [{
          warningOrderId: this.orderData.warningOrderId,
          platformCode:this.orderData.accessNode,
          picUrl:this.orderData.imgList
        }]
        let fileName = '告警图片下载';
        let url = '/export/alarm/order/downLoadImgsLocalTower';
        params.name = "中国铁塔"; // 铁塔视角固定值
        if(location.href.includes('eventQuery')) {
          params.orderIdDownLoadType = "1"; // 其他事件下载查询工单表，标识为1
        }
        if(this.$route.query.pageType === 'recycleBin') {
          if(this.$route.query.page == '11') {
            params.orderIdDownLoadType = "2"; // 回收站标识为2
          }else {
            params.orderIdDownLoadType = "1";
          }
        }
        this.imgLoading = true;
        downLoadZipPost(url,fileName,params,this.dowImgsCallback);
      }

    },
    dowImgsCallback(flag){
      this.imgLoading = false;
      if(flag) {
        this.$message.success("下载告警图片成功")
      } else {
        this.$message.error("下载告警图片失败")
      }
    },
    downAlarmVideo(){
      let params = {
        warningOrderId:this.orderData.warningOrderId,
        videoUrls:this.orderData?.videoUrl?.split(','),
        platformCode:this.orderData.accessNode
      };
      if(!params.videoUrls?.length) {
        return this.$message.warning("当前告警没有告警视频。")
      }
      let url = '/export/alarm/order/downloadLocalVideos';
      let fileName = "告警视频下载";
      if(!this.$store.getters.userInfo.tenantId) {
        params.name = "中国铁塔";
      }
      this.videoLoading = true;
      downLoadZipPost(url,fileName,params,this.downVideoCallback);
    },
    /**
     * 把dom转为图片以blob对象输出
     * @param element dom
     * @returns {Promise}
     */
    htmlElementToBolb(element) {
      return new Promise((resolve, reject) => {
        html2canvas(element).then(canvas => {
          canvas.toBlob((blob) => {
            // Blob 对象已经准备好
            resolve({
              status: true,
              blob
            });
          }, 'image/png'); // 第二个参数是 MIME 类型
        }).catch(error => {
          reject(error);
        });
      });
    },
    /**
     * 导出告警文件
     */
    async downAlarmFile() {
      // let url = '/export/alarm/order/upload';
      const element = document.querySelector('.medias-map-component .dialog_map_big')
      console.log(element, "element")
      if (element || this.mapDom) {
        this.fileLoading = true;
        setTimeout(async () => {
          const dom = this.mapDom ? this.mapDom : element
          const result = await this.htmlElementToBolb(dom);
          if (result.status) {
            this.downFile(result)
          }
        }, 10)
      }
    },
    downFile(result) {
      let url = '/export/alarm/order/exportEventInfo';
      const blob = result.blob;
      const fromData = new FormData();
      fromData.append('file', blob)
      fromData.append('warningOrderId', this.orderData.warningOrderId)
      fromData.append('orderStatus', this.orderData.orderStatus)
      fromData.append('exportSource', this.exportSource)
      if(getQueryString('page') === '12') {
        fromData.append('exportType', '2')
      }
      if(getQueryString('page') === '13') {
        fromData.append('exportType', '1')
      }
      if(this.orderData.horiAzimuthAngle) { fromData.append('horiAzimuthAngle',this.orderData.horiAzimuthAngle) }
      if(this.orderData.devicePitch) { fromData.append('devicePitch',this.addAngleStr(this.orderData.devicePitch)) }
      if(this.orderData.deviceHorizontal) { fromData.append('deviceHorizontal',this.addAngleStr(this.orderData.deviceHorizontal)) }
      const imgUrl = URL.createObjectURL(blob);
      console.log(imgUrl, "base64Image")
      downLoadZipPost(url, `${this.formatDateTimeInChinese(this.orderData.alarmTime)} ${this.orderData.alarmBody}`, fromData, (status) => {
        this.fileLoading = false;
        status ? $message.s('下载告警文件成功') : $message.e('下载告警文件失败')
      })
    },
    downVideoCallback(flag){
      this.videoLoading = false;
      if(flag) {
        this.$message.success("下载告警视频成功")
      }else {
        this.$message.error("下载告警视频失败")
      }
    },
    /**
     * 设置Map dom 容器
     */
    setMapElement() {
      const wrapper = document.querySelector('#mapbox-wrapper');
      wrapper.innerHTML = ''; // 清空存储地图dom的容器
      this.mapDom.classList.add('down_alarm_file_map_dom')
      wrapper.appendChild(this.mapDom)
    },
    /**
     * 将Map dom 移动回原位置
     */
    moveMapDom() {
      const dom = document.querySelector('.down_alarm_file_map_dom');
      if(!dom) { return }
      dom.classList.remove('.down_alarm_file_map_dom')
      const wrapper = document.querySelector('.medias-map-component .event-mapol');
      wrapper.appendChild(dom)
    },
    /**
     * 将日期字符转化为年月日时分秒
     * @param dateString
     * @returns {string}
     */
    formatDateTimeInChinese(dateString) {
      // 解析日期字符串为Date对象
      const date = new Date(dateString);

      // 获取并格式化各个部分
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      // 拼接结果，并添加中文词汇
      return `${year}年${month}月${day}日 ${hours}时${minutes}分${seconds}秒`;
    }
  }
}
</script>

<style lang="scss" scoped>
.event-header {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin:0px 24px;
  border-bottom: 1px solid #F0F0F0;
  color: #606266;
  /deep/.el-button {
    padding: 0;
    color: #606266;
  }
  &.disabled {
    cursor: not-allowed;
    opacity: 0.4;
  }
  .change-alarm {
    cursor: pointer;
    height: 100%;
    display: flex;
    align-items: center;
    .icon {
      margin: 0 5px;
    }
  }
  .diabled {
    cursor: not-allowed;
    opacity: 0.5;
    user-select:none;
  }
  .right {
    display: flex;
    align-items: center;
  }
  .down-img {
    margin-right: 10px;
    font-size: 14px;
  }
  /deep/ .down-img>span{
    display: flex;
    align-items: center;
  }
}
.down-file {
  display: flex;
  align-items: center;
  margin-right: 12px;
  ::v-deep span {
    display: flex;
    align-items: center;
  }
}
.ml-6 {
  margin-left: 6px;
}
.pt-2 {
  padding-top: 2px;
}
</style>
<style lang="scss">
.down_alarm_file_map_dom {
  height: 100%;
  aspect-ratio: 16 / 9;
}
</style>
